package me.zhengjie.modules.quartz.task.onlyOnce;

import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.service.other.domain.CityCompany;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.domain.PropertyPhoto;
import com.qiaofang.applet.service.property.service.PropertyService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: youqing.yang
 * @Create: 2021/01/20 17:01
 * @Description:
 **/
@Slf4j
@Component
public class PropertyPhotoFixTask {

    private static final String PHOTO_CATEGORY = "zipai";

    private static final Integer PAGE_SIZE = 200;


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private CityCompanyService cityCompanyService;

    public void run() {
        //全部公司
        log.info("PropertyPhotoFixTask run start");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("status", match -> match.exact())
                .withIgnoreNullValues();
        CityCompany cityCompany = new CityCompany();
        cityCompany.setStatus(1);
        Iterable<CityCompany> allCityCompany = cityCompanyService.findAll(Example.of(cityCompany, matcher));
        allCityCompany.forEach(item -> {
            long start = System.currentTimeMillis();
            log.info("开始处理公司:{}的房源图片数据,开始时间:{}", item.getCompanyUuid(), new Date());
            fixPropertyPhoto(item.getCompanyUuid(), item.getCorporationCode());
            log.info("完成处理公司:{}的房源图片数据,耗时:{}ms", item.getCompanyUuid(), System.currentTimeMillis() - start);
        });
        log.info("PropertyPhotoFixTask run end");
    }


    public void fixPropertyPhoto(String companyUuid, String corporationCode) {

        Query query = new Query(Criteria.where("corporationCode").is(corporationCode));
        query.addCriteria(Criteria.where("companyUuid").is(companyUuid));
        query.addCriteria(Criteria.where("imageUrls.0").exists(true));
        long count = mongoTemplate.count(query, Property.class);
        log.info("{}公司总数据量：{}", companyUuid, count);
        if (count > 0) {
            PageRequest pageable = PageRequest.of(0, PAGE_SIZE);
            //处理第一页数据
            updateProperty(query, pageable);
            log.info("已经处理完成公司{}第一页的数据!",companyUuid);
            int pageNum = ((int) count + PAGE_SIZE - 1) / PAGE_SIZE;
            log.info("公司{}总页数大小:{}", companyUuid, pageNum);
            if (pageNum < 1) {
                return;
            }
            for (int startPage = 1; startPage <= pageNum; startPage++) {
                PageRequest pageable1 = PageRequest.of(startPage, PAGE_SIZE);
                updateProperty(query, pageable1);
                log.info("已经处理完成公司:{}第{}页的数据!", companyUuid, startPage);
            }
        }
    }

    private void updateProperty(Query query, Pageable pageable) {
        String domainUrl = ImageUtil.HTTP + ImageUtil.IMAGE_URL + "/";
        List<Property> propertyList = mongoTemplate.find(query.with(pageable), Property.class);
        for (Property property : propertyList) {
            if (!CollectionUtils.isEmpty(property.getPhotoList())) {
                List<String> imageUrls = null;
                try {
                    imageUrls = property.getPhotoList().stream().filter(f -> !f.getPhotoCategory().contains(PHOTO_CATEGORY))
                            .sorted(Comparator.comparing(PropertyPhoto::getPhotoIndex))
                            .map(propertyPhoto -> {
                                propertyPhoto.setPhotoURL(domainUrl + propertyPhoto.getPhotoURL());
                                return propertyPhoto;
                            }).map(PropertyPhoto::getPhotoURL).collect(Collectors.toList());
                } catch (Exception e) {
                    log.info("报错:{},{}", e.getMessage(), JSONObject.toJSONString(e));
                }
                property.setImageUrls(imageUrls);
            }
        }
        propertyService.saveAll(propertyList);
    }



}
